package com.qax.task.cron;

import com.qax.task.cron.support.ReschedulingRunnable;

import java.util.concurrent.*;


/**
 *  The underlying implementation of the specific scheduler, here the default time round scheduler
 *
 * @author leiliang
 */
public class ThreadPoolTaskScheduler implements  TaskScheduler {

    ScheduledExecutorService scheduledExecutor =new  ScheduledThreadPoolExecutor(
            Runtime.getRuntime().availableProcessors() << 2,
            new ThreadPoolExecutor.DiscardPolicy());

    /**
     * Return the underlying ScheduledExecutorService for native access.
     * @return the underlying ScheduledExecutorService (never {@code null})
     * @throws IllegalStateException if the ThreadPoolTaskScheduler hasn't been initialized yet
     */
    public ScheduledExecutorService getScheduledExecutor() throws IllegalStateException {
        return this.scheduledExecutor;
    }

    @Override
    public ScheduledFuture<?> schedule(Runnable task, Trigger trigger) throws TaskRejectedException {
        ScheduledExecutorService executor = getScheduledExecutor();
        try {
            return new ReschedulingRunnable(task, trigger, executor).schedule();
        }
        catch (RejectedExecutionException ex) {
            throw new TaskRejectedException("Executor [" + executor + "] did not accept task: " + task, ex);
        }
    }
}
